
var url = 'http://47.105.118.98:9013'
layui.use(['form', 'layer', 'laydate', 'table'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        table = layui.table;
    // 查看文件表格
    var option123 = {
        elem: "#demo",
        id: "demo",
        url: url + "/document/querybyuseridfilename",
        method: "post",
        headers: {
            token: localStorage.getItem("token"),
        },
        request: {
            pageName: "currentPage", //页码的参数名称，默认：page
            limitName: "size", //每页数据量的参数名，默认：limit
        },
        where: {
            userid: localStorage.getItem("id"),
            //       keywords: ""
            filename: ""
        },

        parseData: function (res) {
            console.log(res);
            return {
                code: "0",
                data: setData(res.data.records),
                count: res.data.total,
            };

        },
        height: "full-120",
        text: {
            none: "暂无数据", //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        },
        page: true,
        cols: [
            [{
                type: "checkbox",
                width: 80,
                fixed: "left",
            },
            {
                field: "xvhao",
                type: "numbers",
                title: "序号",
                align: "center",
                width: 80,
            },
            {
                field: "createtime",
                title: "创建时间",
                align: "center",
                width: 180,
                sort: true,
                templet: function (d) {
                    var t1 = d.createtime
                    return util.toDateString(t1);
                }
            },


            {
                field: "filename",
                title: "文件名",
                align: "center",
            },
            {
                field: "geshi",
                title: "格式",
                align: "center",
                width: 100
            },
            {
                fixed: "right",
                width: 180,
                title: "操作",
                toolbar: "#chakanBtn2",
                align: "center",
            },
            ],
        ],
    };
    function setData(data) {

        data.forEach(item => {
            //  item.createtime = layui.util.toDateString(data.createtime * 1000, 'yyyy-MM-dd HH:mm:ss')
            var s = item.filepath.split("/")
            //     var n = s[3].split("_")
            var m = s[3].split(".")
            // item.fileName = n[0]
            item.geshi = m[1]
        });
        return data
    }
    // 用户表格
    option = {
        elem: '#demo1',
        id: 'demo2',
        url: url + '/user/querybyuserid',
        method: 'post',
        page: true,
        height: "full-140",

        text: {
            none: '暂无相关数据' //默认：无数据
        },
        request: {
            pageName: "currentPage", //页码的参数名称，
            limitName: "size", //每页数据量的参数名，
        }
        , where: {
            name: "",
            id: ""
            // keywords: "",
        },
        headers: {
            token: localStorage.getItem('token')
        },
        parseData: function (res) { //res 即为原始返回的数据
            console.log(res)
            return {
                "code": 0, //解析接口状态
                //    "msg": res.message, //解析提示文本
                data: res.data.records,
                count: res.data.total,
            };

        },


        //表头
        cols: [
            [{
                type: "checkbox",//复选框
                fixed: "left",
                width: 50
            }, {
                field: 'id',
                type: 'numbers',
                title: '序号',
                align: 'center',
                width: 80
            },
            {
                field: 'username',
                title: '用户名',
                align: 'center'
            },
            {
                field: 'password',
                title: '密码',
                align: 'center'
            },
            {
                title: '操作',
                templet: '#chakanBtn',
                fixed: "right",
                align: "center",
                width: 400
            }
            ]
        ],
    };
    var tableIns = table.render(option);
    var tableIns123 = table.render(option123);
    util = layui.util

    //添加用户
    $("#addTableDuty_btn").on("click", function () {
        layer.open({
            type: 1,
            title: '添加用户',
            content: $('#addTableDuty'),
            area: ['900', '300'],
        })
    }),
        form.on('submit(add)', function (data) {
            var data1 = {};
            data1.username = data.field.userName;
            data1.password = data.field.password;
            data1.name = data.field.userName;
            console.log(data1)
            $.ajax({
                url: url + "/user/add",
                method: "post",
                data: data1,
                headers: {
                    token: localStorage.getItem('token')
                },
                success: function (data) {
                    // console.log(data)
                    if (data.code === 200) {
                        layer.closeAll();
                        tableIns.reload();
                        layer.msg("添加成功！")
                    } else {
                        layer.msg(data.msg)
                    }
                }

            })
        });
    //搜索查看文件

    $("#chaxun123").click(function () {
        //重新加载表格
        console.log($("#sousuo123").val())
        var name = $("#sousuo123").val()
        table.reload('demo', {
            where: { //设定异步数据接口的额外参数，任意设
                filename: name
            },
            page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    });
    // 用户列表根据选中行删除选中内容
    $("#delete_Btn").on("click", function () {
        layer.confirm('确定删除选中内容？', {
            btn: ['确定', '取消']
        }, function () {
            var checkStatus = table.checkStatus('demo2'); //即为基础参数 id 对应的值
            var data1 = '';
            checkStatus.data.forEach((item) => {
                data1 += item.id + ',';
            });
            data1 = data1.substr(0, data1.length - 1)
            var data2 = data1.split(",")
            //  console.log(data1)
            //  console.log(data2)
            if (data2.length !== 0) {
                for (var i = 0; i < data2.length; i++) {
                    $.ajax({
                        url: url + "/user/deletebyuserid",
                        method: "post",
                        data: {
                            id: data2[i]
                        },
                        headers: {
                            token: localStorage.getItem('token')
                        },
                        success: function (data) {
                            // console.log(data)
                            if (data.code === 200) {
                                tableIns.reload();
                                layer.msg('删除成功！')

                            } else {
                                layer.msg("请先选择需要删除的内容！")
                            }

                        },
                        error: function (err) {
                            layer.msg('删除失败！')
                        }
                    })
                }
            } else {
                layer.msg("请先选择需要删除的内容！", {
                    icon: 2
                });
            }
        }, function () {
            console.log("取消")
        })
    })
    // 查看内容弹窗根据选中行删除选中内容
    $("#delete_Btn2").on("click", function () {
        layer.confirm('确定删除选中内容？', {
            btn: ['确定', '取消']
        }, function () {
            var checkStatus = table.checkStatus('demo'); //即为基础参数 id 对应的值
            var data1 = '';
            checkStatus.data.forEach((item) => {
                data1 += item.id + ',';
            });
            data1 = data1.substr(0, data1.length - 1)
            var data2 = data1.split(",")
            //  console.log(data1)
            //  console.log(data2)
            if (data2.length !== 0) {
                for (var i = 0; i < data2.length; i++) {
                    $.ajax({
                        url: url + "/document/deletebyuserid",
                        method: "post",
                        data: {
                            id: data2[i]
                        },
                        headers: {
                            token: localStorage.getItem('token')
                        },
                        success: function (data) {
                            // console.log(data)
                            if (data.code === 200) {
                                tableIns123.reload();
                                layer.msg('删除成功！')

                            } else {
                                layer.msg("请先选择需要删除的内容！")
                            }
                        },
                        error: function (err) {
                            layer.msg('删除失败！')
                        }
                    })
                }
            } else {
                layer.msg("请先选择需要删除的内容！", {
                    icon: 2
                });
            }
        }, function () {
            console.log("取消")
        })

    })
    // 查看内容弹窗根据选中行下载选中内容
    // $("#xiazai_Btn2").on("click", function () {
    //     var checkStatus = table.checkStatus('demo'); //即为基础参数 id 对应的值
    //     var data1 = '';
    //     var data3 = '';
    //     checkStatus.data.forEach((item) => {
    //         data1 += item.filepath + ',';
    //         data3 += item.filename + ',';
    //     });
    //     data1 = data1.substr(0, data1.length - 1)
    //     data3 = data3.substr(0, data3.length - 1)
    //     var data2 = data1.split(",")
    //     var data4 = data3.split(",")
    //     console.log(data1)
    //     console.log(data2)
    //     console.log(data3)
    //     console.log(data4)
    //     if (data2.length !== 0) {
    //         for (var i = 0; i < data2.length; i++) {
    //             var path = url + data2[i]
    //             console.log(path)
    //             var x = new XMLHttpRequest();
    //             x.open("GET", path, true);
    //             x.responseType = 'blob';
    //             var name = data4[i];
    //             function getname() {
    //                 return name
    //             }
    //             x.onload = function (e) {
    //                 var url1 = window.URL.createObjectURL(x.response)
    //                 var aa = document.createElement("a");
    //                 aa.href = url1
    //                 aa.download = getname();
    //                 aa.style.display = "none";
    //                 document.body.appendChild(aa);
    //                 aa.click();
    //                 document.body.removeChild(aa)
    //             }
    //             x.send(null);

    //         }
    //     } else {
    //         layer.msg("请先选择需要删除的内容！", {
    //             icon: 2
    //         });
    //     }
    // })
    // 搜索
    $('.sousuo2').keydown(function (e) {
        if (e.keyCode === 13) {
            $("#chaxun123").trigger("click");
            return false
        }
    });
    $('.sousuo1').keydown(function (e) {
        if (e.keyCode === 13) {
            $("#chaxun").trigger("click");
            return false
        }
    });
    $("#chaxun").click(function () {
        //重新加载表格
        table.reload('demo2', {
            where: { //设定异步数据接口的额外参数，任意设
                name: $("#sousuo").val()
            },
            page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    });

    //查看文件列表操作：下载与删除
    table.on('tool(demo)', function (obj) {
        var layEvent = obj.event,
            data1 = obj.data;
        // 下载
        if (layEvent === 'xiazai') {

            var path = url + data1.filepath
            var x = new XMLHttpRequest();
            x.open("GET", path, true);
            x.responseType = 'blob';
            x.onload = function (e) {
                var url1 = window.URL.createObjectURL(x.response)
                var aa = document.createElement("a");
                aa.href = url1
                aa.download = data1.filename
                aa.style.display = "none";
                document.body.appendChild(aa);
                aa.click();
                document.body.removeChild(aa)
            }
            x.send()

            //     var s = data1.filepath.split("/");

        }

        else {
            layer.confirm('确定删除  ' + data1.filename + '  ？', {
                btn: ['确定', '取消']
            }, function () {
                // console.log("确定")
                console.log(data1);
                console.log(data1.id);
                $.ajax({
                    url: url + "/document/deletebyuserid",
                    method: "post",
                    data: {
                        id: data1.id,
                        // keywords: "",
                    },
                    headers: {
                        token: localStorage.getItem('token')
                    },
                    success: function (data) {
                        console.log(data)
                        if (data.code === 200) {
                            tableIns123.reload();
                            layer.msg('删除成功！')

                        } else {
                            layer.msg(data.msg)
                        }

                    },
                    error: function (err) {
                        layer.msg('删除失败！')
                    }
                })
            }, function () {
                console.log("取消")
            })
        }
    })

    // 用户表格列表操作：查看文件，编辑与删除
    table.on('tool(demo2)', function (obj) {
        var layEvent = obj.event,
            data1 = obj.data;
        console.log(data1)
        console.log(data1.id)
        if (layEvent === 'chakan') {
            option123.where.userid = data1.id
            table.reload("demo", option123);
            layer.open({
                type: 1,
                title: '查看文件',
                content: $('#chakanTable'),
                area: ['1000px', '600px'],
                btn: ['确认']
            })

        } else if (layEvent === 'edit') {
            //编辑修改
            console.log(data1)
            $("#editUserName").val(data1.username);
            $("#editPassWord").val(data1.password);
            layer.open({
                type: 1,
                title: '编辑',
                content: $('#editTableDuty'),
                area: ['300px', '250px'],
                btn: ['确认修改', '取消'],
                yes: function (index, layero) {
                    var username1 = $("#editUserName").val();
                    var password1 = $("#editPassWord").val();
                    var data2 = {}
                    data2.username = username1;
                    data2.password = password1;
                    data2.name = username1;
                    data2.id = data1.id;
                    // data2.level = 1
                    // console.log(data2.level)
                    console.log(data2)
                    $.ajax({
                        url: url + "/user/add",
                        method: "post",
                        data: data2
                        ,
                        headers: {
                            token: localStorage.getItem('token')
                        },
                        success: function (data) {
                            //    console.log(data)
                            if (data.code === 200) {
                                layer.closeAll();
                                tableIns.reload();
                                layer.msg("修改成功！")
                            } else {
                                layer.msg(data.msg)
                            }
                        }

                    })
                }
            })
        }
        //删除
        else {
            layer.confirm('确定删除  ' + data1.username + '  ？', {
                btn: ['确定', '取消']
            }, function () {
                console.log(data1);
                $.ajax({
                    url: url + "/user/deletebyuserid",
                    data: {
                        id: data1.id
                    },
                    method: "post",
                    headers: {
                        token: localStorage.getItem('token')
                    },
                    success: function (data) {
                        console.log(data)
                        if (data.code === 200) {
                            tableIns.reload();
                            layer.msg('删除成功！')

                        } else {
                            layer.msg(data.message)
                        }

                    },
                    error: function (err) {
                        layer.msg('删除失败！')
                    }
                })
            }, function () {
                console.log("取消")
            })
        }
    })

});


